package net.sahv.bdyz.api;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sahv.bdyz.model.Member;
import net.sahv.bdyz.model.MemberLoginInfo;
import net.sahv.bdyz.service.MemberLoginInfoService;
import net.sahv.bdyz.service.MemberService;
import net.sahv.bdyz.util.AddressUtils;
import net.sahv.bdyz.util.IPUtil;
import net.sahv.bdyz.util.RegexValidateUtil;
import net.sahv.bdyz.util.SendMessage;
import net.sahv.bdyz.util.VerifyCode;

/**
 * 
 * @author 任凯伟
 *
 */
@Controller("apiLogInController")
@RequestMapping("api/logIn")
public class LogInController {

	@Autowired
	private MemberService memberService;
	// 保存sessionID和username的映射
	private static HashMap hUserName = new HashMap();
	@Autowired
	private MemberLoginInfoService memberLoginInfoService;
	
	/**
	 * 
	 * @author 作者 : 任凯伟
	 * @date 创建时间：2016年9月7日 上午8:47:31
	 * @version 1.0
	 * @see 登录
	 * @param
	 * @parameter
	 * @since
	 * @return
	 */
	@RequestMapping(value="/landing",method=RequestMethod.POST)
	public  @ResponseBody String landing(HttpServletRequest request,String telphone,String password,Integer language){
		HttpSession session = request.getSession();
		if(RegexValidateUtil.checkMobileNumber(telphone)){
			Member member=memberService.selectUserMessage(telphone);
			if(member != null && !member.equals("")){
				if (member.getmIsDelete() == 1) {
					return "-2";
				}else if(member.getmIsDelete() == 2){
					return "3";
				}
				if (DigestUtils.md5Hex(password).equals(member.getmPassword())) {
					if (hUserName.containsValue(telphone)) {
						// 遍历原来的hUserName，删除原用户名对应的sessionID(即删除原来的sessionID和username)
						Iterator iter = hUserName.entrySet().iterator();
						while (iter.hasNext()) {
							Map.Entry entry = (Map.Entry) iter.next();
							Object key = entry.getKey();
							Object val = entry.getValue();
							if (((String) val).equals(telphone)) {
								hUserName.remove(key);
							}
						}
						// 添加现在的sessionID和username
						hUserName.put(session.getId(), telphone);
					} else {// 如果该用户没登录过，直接添加现在的sessionID和username
						hUserName.put(session.getId(), telphone);
					}
					session.setAttribute("hUserName", hUserName);
					session.setAttribute("member", member);
					session.setAttribute("telphone", member.getmPhone());
					session.setAttribute("mId", member.getmId());
					// 添加会员登陆日志
					String ipString = IPUtil.getClientIP(request);
					MemberLoginInfo memberLoginInfo = new MemberLoginInfo();
					memberLoginInfo.setmId(member.getmId());
					memberLoginInfo.setMliIp(ipString);
					memberLoginInfo.setMliCreateTime(new Date());
					memberLoginInfo.setMliIsDelete(0);
					memberLoginInfoService.insert(memberLoginInfo);
					if(member.getmLanguage()==1){
						session.setAttribute("language", "zh_cn");
					}else if(member.getmLanguage()==2){
						session.setAttribute("language", "en");
					}
					return "1";
				}else{
					return "0";
				}
			}else{
				return "2";
			}
		}else{
			return "-1";
		}
	}
	
	/**
	 * 
	 * @author 作者 : 任凯伟
	 * @date 创建时间：2016年9月7日 上午8:48:02
	 * @version 1.0
	 * @see 注册
	 * @param
	 * @parameter
	 * @since
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/register")
	public String register(HttpServletRequest request, String telphone, String password, String validateCode,
			Integer language, String type, String merchantType, String realname) {
		if(RegexValidateUtil.checkMobileNumber(telphone)){
			// 账号是否是刚才发送验证码的那个
			String reTelphone = (String) request.getSession().getAttribute("telphone");
			if (!telphone.equals(reTelphone)) {
				return "3";// 验证码与注册手机号不符！
			}
			Member member=memberService.selectUserMessage(telphone);
			if(member == null){
				String a = (String) request.getSession().getAttribute("validateNum");
				if (a != null && a.equals(validateCode.toUpperCase())) {// 验证码验证正确
					Calendar cal = Calendar.getInstance();
					IPUtil ipUtil = new IPUtil();
					String ip = ipUtil.getClientIP(request);
					Map<String, Object> map = new HashMap();
					if (ip != null) {
						AddressUtils addressUtils = new AddressUtils();
						try {
							map = addressUtils.getAddresses("ip=" + ip, "utf-8");
						} catch (UnsupportedEncodingException e) {
						}
					}
					Member members = new Member();
					members.setmPhone(telphone);
					members.setmPassword(DigestUtils.md5Hex(password));
					members.setmCreateTime(new java.sql.Date(cal.getTime().getTime()));
					members.setmNickname(realname);
					members.setmImg("m_img.jpg");
					members.setmLanguage(language);
					members.setmIsDelete(0);
					members.setmVip(0);
					members.setmType(type);
					members.setmMerchantType(merchantType);
					members.setmProvince(map.get("regionId").toString());
					members.setmCity(map.get("cityId").toString());
					members.setmArea(map.get("countyId").toString());
					int i = memberService.insert(members);
					if (i > 0) {
						request.getSession().setAttribute("validateNum", "");
						return "1";// 注册成功
					}
				} else {
					return "-1";// 验证码错误或已失效
				}
			}else{
				return "-2";// 账号已注册
			}
			
		}else{
			return "2";// 手机号格式错误
		}
		return "0";// 注册失败
		
	}
	
	/**
	 * 
	 * @author 作者 : 任凯伟
	 * @date 创建时间：2016年8月17日 上午9:52:16
	 * @version 1.0
	 * @see 获取验证码
	 * @param
	 * @parameter
	 * @since
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getcode")
	public ApiResult getcode(HttpServletRequest request, String telphone) {
		ApiResult result = new ApiResult();
		// 判断手机号参数是否为空
		if(telphone!=null && ! telphone.equals("")){
			// 判断手机号格式是否正确
			if(RegexValidateUtil.checkMobileNumber(telphone)){
				// 随机生成6位数字
				String validateNum = VerifyCode.getRandomString(6);
				// String validateNum = "123456";
				boolean flag = SendMessage.send(telphone, "您的验证码为:" + validateNum + "。");// 手机号，内容
				// 发送验证码
				// boolean flag = true;
				// 缓存到session中 有效时间3分钟
				if (flag) {
					HttpSession session = request.getSession();
					session.setAttribute("telphone", telphone);
					session.setAttribute("validateNum", validateNum);
					session.setMaxInactiveInterval(180);
					result.msg.status = 1;
				} else {
					result.msg.status = 0;
				}
			}else{
				result.msg.status = 0;
				result.msg.desc = "手机号格式错误";
				return result;
			}
		}else{
			result.msg.status = 0;
			result.msg.desc = "手机号参数不合法";
			return result;
		}
		return result;
   }

	/**
	 * 
	 * @author 作者 : 任凯伟
	 * @date 创建时间：2016年8月18日 上午9:51:23
	 * @version 1.0
	 * @see 找回密码
	 * @param
	 * @parameter
	 * @since
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/forgotPassword")
	public String forgotPassword(HttpServletRequest request, String telphone, String password, String validateCode,
			Integer language) {
		if(RegexValidateUtil.checkMobileNumber(telphone)){
			Member member=memberService.selectUserMessage(telphone);
			if(member !=null && ! member.equals("")){
				String a = (String) request.getSession().getAttribute("validateNum");
				if (a != null && a.equals(validateCode.toUpperCase())
						&& telphone.equals(request.getSession().getAttribute("telphone"))) {// 验证码验证正确
					int i = memberService.updatePassword(DigestUtils.md5Hex(password), telphone);
					if (i > 0) {
						request.getSession().setAttribute("validateNum", "");
						return "1";// 密码重置成功
					}
				} else {
					return "-1";// 验证码错误或已失效
				}
			}else{
				return "2";// 当前手机号未注册
			}
		}
		return "0";// 密码重置失败
	}

	/**
	 * 
	 * @author 作者 : 任凯伟
	 * @date 创建时间：2016年8月17日 上午9:24:25
	 * @version 1.0
	 * @see 判断手机号是否已注册
	 * @param
	 * @parameter
	 * @since
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/isTelExist")
	public boolean isTelExist(String telphone) {
		if (telphone != null) {
			Member member = memberService.findByTel(telphone);
			if (member != null) {
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

	/**
	 * 
	 * @author 作者 : 任凯伟
	 * @date 创建时间：2016年8月18日 上午9:44:26
	 * @version 1.0
	 * @see 忘记密码时判断手机号是否已注册
	 * @param
	 * @parameter
	 * @since
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/isTelRegister")
	public boolean isTelRegister(String telphone) {
		if (telphone != null) {
			Member member = memberService.findByTel(telphone);
			if (member != null) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
}
